//
//  HCAddressManagerController.m
//  HappyChildren
//
//  Created by jiayibai-02por on 2017/6/10.
//  Copyright © 2017年 WillyZhao. All rights reserved.
//

#import "HCAddressManagerController.h"
#import "HCAddressCell.h"

@interface HCAddressManagerController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *addressTable;
@property (nonatomic, strong) UIButton *addAddressButton;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) NSMutableArray *cellState;
@property (nonatomic, strong) NSDictionary *currentData;

@end

@implementation HCAddressManagerController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.textTitle = self.dataObject;
    self.dataArray = [NSArray array];
    self.cellState = [NSMutableArray array];
    self.currentData = [NSDictionary dictionary];
    self.dataRequest.delegate = self;
    [self initTableView];
    
    UIButton *finishButton = [[UIButton alloc] initWithFrame:CGRectMake(self.headerView.frame.size.width-60, 20, 60, 44)];
    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [finishButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [finishButton addTarget:self action:@selector(finishButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:finishButton];
}

- (void)finishButtonClick:(UIButton *)sender {
    
    //点击完成
    if (self.currentData) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"currentAddress" object:nil userInfo:@{@"address":self.currentData}];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"getaddress" object:nil userInfo:@{@"address":self.currentData}];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initCellStateArray:(NSArray *)addressData {
    
    self.cellState = [NSMutableArray arrayWithCapacity:self.dataArray.count];
    for (int i = 0; i < self.dataArray.count; i++) {
        
        if ([[self.dataArray[i] objectForKey:@"stat"] integerValue] == 1) {
            
            self.cellState[i] = [NSNumber numberWithBool:YES];
            self.currentData = self.dataArray[i];
        }
        else {
            
            self.cellState[i] = [NSNumber numberWithBool:NO];
        }
    }
    NSLog(@"cel状态：%@",self.cellState);
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    self.addAddressButton.hidden = YES;
    
    if (self.currentData) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"currentAddress" object:nil userInfo:@{@"address":self.currentData}];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"getaddress" object:nil userInfo:@{@"address":self.currentData}];
    }
}

- (void)dealloc {
    
    NSLog(@"HCAddressManagerController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"getaddress" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"currentAddress" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.addAddressButton.hidden = NO;
    [self.dataRequest post_HCMineAddressList:HCGETUSER(@"userid")];
}

- (void)initTableView {
    
    self.addressTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_width, self.centerView.frame.size.height-49) style:UITableViewStylePlain];
    self.addressTable.delegate = self;
    self.addressTable.dataSource = self;
    [self.addressTable registerNib:[UINib nibWithNibName:@"HCAddressCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"addresscell"];
    [self.centerView addSubview:self.addressTable];
    self.addressTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.addAddressButton = [[UIButton alloc] initWithFrame:CGRectMake(0, Screen_height-45, Screen_width, 45)];
    [self.addAddressButton addTarget:self action:@selector(addAddressAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.addAddressButton setImage:[UIImage imageNamed:@"add_address_img"] forState:UIControlStateNormal];
    [YBKShareAppDelegate.window addSubview:self.addAddressButton];
}

- (void)dataRequesterFinish:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveDictionary:(NSDictionary *)dictionary {
    
    if (aType == HC_MINEADDRESSLIST_TYPE) {
        
        NSArray *arr = [dictionary objectForKey:@"address"];
        if (arr.count > 0) {
            
            NSLog(@"获取地址列表:%@",dictionary);
            self.dataArray = arr;
            [self initCellStateArray:arr];
        }
        [self.addressTable reloadData];
        
    }else{
        NSLog(@"设置默认选中:%@",dictionary);
    }
}

- (void)dataRequesterFail:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveErrorDictionary:(NSDictionary *)dictionary {
    
    NSLog(@"请求失败");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 84;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"addresscell";
    HCAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[HCAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.nameLabel.text = [self.dataArray[indexPath.row] objectForKey:@"name"];
    cell.phoneLabel.text = [self.dataArray[indexPath.row] objectForKey:@"phone"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if ([self.cellState[indexPath.row] boolValue]) {
        
        NSString *str = [NSString stringWithFormat:@"[默认地址]%@",[self.dataArray[indexPath.row] objectForKey:@"address"]];
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:str];
        [aString addAttribute:NSForegroundColorAttributeName value:YBKRGBCOLOR(240, 96, 96, 1) range:NSMakeRange(0,6)];
        cell.addressLabel.attributedText = aString;
    }
    else {
        
        cell.addressLabel.text = [self.dataArray[indexPath.row] objectForKey:@"address"];
    }
    __weak typeof (self)weakSelf = self;
    [cell setDidClickChooseButtonBlock:^(HCAddressCell *cell){
        
        
        //选中cell
        NSInteger index = [tableView indexPathForCell:cell].row;
        BOOL obj = [[weakSelf.cellState objectAtIndex:index] boolValue];
        if (indexPath.row == index && obj) {
            
            return;
        }
        
        if (!obj) {
            
            [weakSelf.dataRequest post_HCDefault_address:[NSString stringWithFormat:@"%@",[weakSelf.dataArray[indexPath.row] objectForKey:@"id"]]];
        }
        obj = !obj;
        for (int i = 0; i < weakSelf.cellState.count; i++) {
            
            if (i != index) {
                
                [weakSelf.cellState replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
            }
            else {
                
                [weakSelf.cellState replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:obj]];
            }
        }
        [weakSelf.addressTable reloadData];
        weakSelf.currentData = [weakSelf.dataArray objectAtIndex:index];
    }];
    
    if (self.cellState.count > 0) {
        
        cell.isClicked = [self.cellState[indexPath.row] boolValue];
    }
    
    return cell;
}

- (void)addAddressAction:(UIButton *)sender {
    
    [self pushChildrenViewController:@"HCAddNewAddressController" parameterObject:nil dataObject:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
